/**
 * Created by CooTek on 2015/7/21.
 */

var loadReady = (function() {

    var imgArray = [];          // 加载数组，存入img的url
    var loadedImages = [];      // 已经加载完成的图片数量
    var loadHandler = null;     // 全部加载完毕 的回调函数
    var coverId = 'load-cover';
    var maxDuration = 5000;     // 加载持续时间，过了这段时间还没刷出则放弃加载过程，直接显示内容
    var coverIsOut = false;

    /**
     * 初始化工作
     * @param callback -- 回调函数
     */
    function init(callback) {
        var defaultCallback = function() {
            coverFadeOut(coverId);
        };

        document.getElementById(coverId).className += ' fade-out fade-out-begin';
        setTimeout(function() {
            if (!coverIsOut) {
                coverFadeOut.call(this);
            }
        }, maxDuration);

        loadHandler = callback || defaultCallback;
        loadAllImages();
    }

    /**
     * 加载遮罩逐渐消失
     * @param coverId
     * @param duration
     * @param framesPerSecond
     */
    function coverFadeOut(coverId) {
        coverIsOut = true;
        document.getElementById(coverId).className = document.getElementById(coverId).className.replace(/fade\-out\-begin/g, 'fade-out-end');
        document.body.className = document.body.className.replace(/overflow\-hidden/g, '');
    }

    /**
     * 加载遮罩逐渐消失 （setTimeout兼容）
     * @param coverId
     * @param duration
     * @param framesPerSecond
     */
    function coverFadeOutTimeout(coverId, duration, framesPerSecond) {
        coverId = coverId || 'load-cover';
        duration = duration || 1;
        framesPerSecond = framesPerSecond || 25;

        var frames = 0;
        while(frames <= framesPerSecond) {
            doTimeout(1-frames/framesPerSecond, frames);
            frames++;
        }


        function doTimeout(alpha, frames) {

            if (alpha === 0) {
                setTimeout(function() {
                    document.getElementById(coverId).className += ' display-none';
                }, (duration*1000) * frames / framesPerSecond);

            } else {
                setTimeout(function() {
                    document.getElementById(coverId).style.opacity = alpha.toString() || '1';
                }, (duration*1000) * frames / framesPerSecond);
            }
        }
    }

    /**
     * 载入页面中所有img
     */
    function loadAllImages() {
        var images = document.images;
        for (var i = 0; i < images.length; i++) {
            if (images[i].src) {
                addImageUrl(images[i].src);
            }
        }
    }

    /**
     * 判断图片是否已经全部加载完成
     * @returns {boolean}
     */
    function checkFinish() {
        return loadedImages.length >= imgArray.length;
    }

    /**
     * 增加一张图片到加载数组中
     * @param url
     */
    function addImageUrl(url) {
        if (url in imgArray) {
            return;
        }

        imgArray.push(url);
        bindLoadEvent(url);
    }

    /**
     * 对url的image绑定加载完毕的事件
     * @param url
     */
    function bindLoadEvent(url) {
        var tempImage = new Image();
        tempImage.src = url;

        addLoadEvent(tempImage, function(event) {
            loadedImages.push(event.target.src);
            if ( checkFinish() ) {
                loadHandler.call(loadReady);
            }
        });
    }

    /**
     * 绑定load事件func到元素element上
     * @param element
     * @param func
     */
    function addLoadEvent(element, func) {
        element.addEventListener('load', func);
    }

    /**
     * 移除图像url
     * @param url
     * @returns {boolean}   是否成功
     */
    function removeImageUrl(url) {
        for (var i = 0; i < loadedImages.length; i++) {
            if (loadedImages[i] === url) {
                return false;
            }
        }

        for (var i = 0; i < imgArray.length; i++) {
            if (imgArray[i] === url) {
                imgArray.splice(i,1);
                i--;
            }
        }

        return true;
    }

    return {
        init: init,
        addImageUrl: addImageUrl,
        removeImageUrl: removeImageUrl
    };

})();


loadReady.init();
loadReady.addImageUrl('http://b.zol-img.com.cn/desk/bizhi/image/6/1366x768/1440992943343.jpg');
//loadReady.addImageUrl('http://b.zol-img.com.cn/desk/bizhi/image/6/1366x768/1437465298826.jpg?downfile=1437465298826.jpg');


